const conn = require("../db/CheDb");

const PagerHelper = {
  getQueryResult: function (sql, pager) {
    var sql_total = `select 
            count(1) as total
            from (${sql}) as temp_view;
            `;

    var sql_with_pager = "";

    if (pager) {
      var { page_index, page_size } = pager;
      page_index = page_index || 1;
      page_size = page_size || 10;

      page_index = page_index < 1 ? 1 : page_index;

      var from = (page_index - 1) * page_size + 1;

      sql_with_pager = sql + ` limit ${from},${page_size} `;
    }

    var final_sql = "";
    if (pager) {
      final_sql = sql_with_pager + ";" + sql_total;
    } else {
      final_sql = sql;
    }

    return new Promise((resolve, reject) => {
      conn.query(final_sql, null, (err, rows) => {
        if (err) {
          reject(err);
        } else {
          if (pager) {
            res = {
              list: rows[0],
              total: rows[1][0].total,
            };
          } else {
            res = {
              list: rows,
            };
          }

          resolve(res);
        }
      });
    });
  },
  SuccessRes: function (data) {
    return {
      result_code: 1000,
      result_data: data,
      result_msg: "",
    };
  },
  FailRes: function (msg) {
    return {
      result_code: 0,
      result_data: null,
      result_msg: msg || "操作失败",
    };
  },
  StringIsNullOrEmpty: function (str) {
    str = str || "";

    console.log(str, "======StringIsNullOrEmpty========");
    var b = str.length == 0;

    return b;
  },
  setDeepTree: function (node, arr) {
    var arr = arr || [];

    var children = arr.filters((item) => {
      return node.id == item.parent_id;
    });

    if (children.length > 0) {
      children.forEach((child) => {
        PagerHelper.setDeepTree(child, arr);
      });
    }
    node.children = children;
  },
};

module.exports = PagerHelper;
